//
//  CZOauthController.swift
//  SinaWeiBo
//
//  Created by 刘幼寒 on 5/17/16.
//  Copyright © 2016 刘幼寒. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOauthController: UIViewController
{
    override func loadView()
    {
        //将授权控制器的view换成WebView来显示新浪微博的登录界面（网页登录界面）
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        //设置授权控制器的背景颜色
        self.view.backgroundColor = globalBackgroundColor
        //设置导航栏
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        //title
        navigationItem.title = "登录"
        
        //定义一个URL的字符串https://api.weibo.com/oauth2/authorize?client_id=1885339388&redirect_uri=http://www.baidu.com/
        let urlString: String = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url =  NSURL(string: urlString)
        //webView加载数据是需要请求数据的URL作为参数
        let request = NSURLRequest(URL: url!)
        //在webView里面加载网络数据来显示网页内容
        webView.loadRequest(request)
        
        //加载指示器，显示正在加载
//        SVProgressHUD.showErrorWithStatus(status: String!)显示错误
//        SVProgressHUD.showInfoWithStatus("正在加载")提示信息感叹号，会自动关闭
        SVProgressHUD.showWithStatus("正在加载")//提示信息感叹号，不会自动关闭

        
    }
    
    //MARK: - 点击事件
    //填充
    @objc private func autoFill()
    {
        //document.getElementById('userId').value='15910776481';
        //document.getElementById('passwd').value='han0123abcd';
        let jsString = "document.getElementById('userId').value='15910776481';document.getElementById('passwd').value='han0123abcd';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)

//        CZprint(items: "autoFill")
    }
    
    //取消
    @objc private func close()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    ///weView
    private lazy var webView: UIWebView = UIWebView()

}

///CZOauthController类扩展，webview完成加载后调用代理方法实现一些事情
extension CZOauthController: UIWebViewDelegate
{
    //webView网页加载完成后调用
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
    
    //webView加载网页的时候会调用这个方法，加载一次回调一次，询问我们是否要加载某个请求
    //return true 可以加载这个界面
    //return false 就不加载这个界面
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {

        //点击授权http://www.baidu.com/?code=22d0b8fac90078807d6bdfc1d315c5af
        //点击取消http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //只要不是授权回调地址，是新浪的界面，就让他去加载
        if !request.URL!.absoluteString.hasPrefix(redirect_uri)
        {
            return true
        }
        //是授权回调地址，点击是取消或者授权，不让他去加载，我们自己来做一些事情
        //URL的query：？后面的东西
        else
        {
            //截取回调请求URL问号后的数据
            let query = request.URL!.query!
            let codeString = "code="
            if query.hasPrefix(codeString)
            {
                //如果query是以code=开头表示点击的授权按钮
                //从query中截取code的值，substringFromIndex从指定的位置截取到最后
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                //加载AccessToken,字典转模型，模型保存到沙盒
                CZUserAccountViewModel.sharedInstance.loadAccessToken(code, callBack: { (error) -> () in
                    if error != nil
                    {
                        //出现了错误
                        CZprint(items: "出现了错误：\(error)")
                        SVProgressHUD.showErrorWithStatus("您的网络不给力")
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    }
                    else
                    {
                        //没有出现错误
                        CZprint(items: "没有出现错误")
                        self.close()
                    }
                })
                
                
                //如果urlString里面开头是http或者HTTPS就直接使用这个urlString，如果不是以http或者HTTPS开头AFN会帮我们拼接baseURL
//                let urlString = "oauth2/access_token"
//                //参数
//                let parameters = [
//                    "client_id" : client_id,
//                    "client_secret" : client_secret,
//                    "grant_type" : "authorization_code",
//                    "code" : code,
//                    "redirect_uri" : redirect_uri
//                ]
//                
//                CZNetworkTool.sharedInstance.request(kREQUESTMETHOD.POST, URLString: urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
//                    
//    //                    "access_token" = "2.00p7P_7GotgaDC0667ad0e67pdRQcB";
//    //                    "expires_in" = 157679999;
//    //                    "remind_in" = 157679999;
//    //                    uid = 5885569283;
////                        CZprint(items: "获得AcessToken成功：\(responseObject)")
//                    
//                    //将数据保存到模型当中去
//                    if let result = responseObject as? [String : AnyObject]
//                    {
//                        //字典转模型
//                        let userAccount = CZUserAccount(dict: result)
//                        CZprint(items: userAccount)
//                        let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
//                        //将模型归档到沙盒里面
//                        NSKeyedArchiver.archiveRootObject(userAccount, toFile: userAccountPath)
//                    }
//                    else
//                    {
//                        CZprint(items: "返回数据字典失败了")
//                    }
//                    
//                    }, failure: { (task, error) -> Void in
//                        CZprint(items: "失败了：\(error)")
//                })
            }
            else
            {
                //点击的是取消
                close()
            }
            return false
        }
 

    }
}







